<?php

namespace App;

use App\Models\Comment;
use App\Models\Doc;
use App\Models\Liveroom;
use App\Models\Withdraw;
use App\Models\WxUser;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;
use Overtrue\LaravelFollow\Traits\CanBeFollowed;
use Overtrue\LaravelFollow\Traits\CanFollow;
use Overtrue\LaravelFollow\Traits\CanLike;
use Overtrue\LaravelFollow\Traits\CanSubscribe;

class User extends Authenticatable
{
    use HasApiTokens, Notifiable, CanSubscribe, CanLike, CanFollow, CanBeFollowed;
    protected $guarded = [];
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function wx_user()
    {
        return $this->hasOne(WxUser::class, 'user_id');
    }

    public function docs()
    {
        return $this->hasMany(Doc::class);
    }

    public function comments()
    {
        return $this->hasMany(Comment::class, 'user_id');
    }

    public function withdraw()
    {
        return $this->hasMany(Withdraw::class, 'user_id');
    }

    public function liveroom()
    {
        return $this->hasOne(Liveroom::class, 'user_id');
    }

    public static function getLiveroom($user)
    {
        $user->liveroom()->firstOrCreate([], [
            'title' => $user->name,
            'description' => $user->name,
            'avatar' => $user->avatar,
            'qrcode' => ''
        ]);
    }

    public static function addWxUser($wx_user, $phone = '')
    {
        $user = self::query()->create([
            'role_id' => 2,
            'name' => $wx_user->nick_name ?? str_random(6),
            'email' => md5($wx_user->id) . '@yundocs.com',
            'password' => bcrypt($wx_user->open_id),
            'avatar' => $wx_user->avatar,
            'phone' => $phone
        ]);
        $wx_user->user_id = $user->id;
        $wx_user->save();
        $user->liveroom()->create([
            'title' => $user->name,
            'description' => $user->name,
            'avatar' => $user->avatar,
            'qrcode' => ''
        ]);
        return $user;

    }
}
